package org.yang.database.orm.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.yang.common.utils.jwt.JwtTokenAnalysisUtli;

import java.time.LocalDateTime;

import static org.yang.database.orm.constant.MetaConstant.*;


/**
 * 自动填充拦截
 *
 * @author: Islands
 * @create: 2024-02-29 20:00
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    /**
     * 获取用户
     * @return
     */
    static String userId(){
        try {
            return JwtTokenAnalysisUtli.useId().toString();
        }catch (NullPointerException e){
            log.error("获取用户异常");
            return DEFAULT_NAME;
        }
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter(LOGIC)){
            this.strictInsertFill(metaObject, LOGIC, Integer.class, DEFAULT_LOGIC);
        }
        if (metaObject.hasGetter(CREATED_TIME)){
            this.strictInsertFill(metaObject, CREATED_TIME, LocalDateTime.class, LocalDateTime.now());
        }
        if (metaObject.hasGetter(CREATED_BY)){
            this.strictInsertFill(metaObject, CREATED_BY, String.class, userId());
        }
        if (metaObject.hasGetter(REVISION)){
            this.strictInsertFill(metaObject, REVISION, Integer.class, DEFAULT_REVISION);
        }
        if (metaObject.hasGetter(UPDATED_BY)){
            this.strictUpdateFill(metaObject, UPDATED_BY, String.class, userId());
        }
        if (metaObject.hasGetter(UPDATED_TIME)){
            this.strictUpdateFill(metaObject, UPDATED_TIME, LocalDateTime.class, LocalDateTime.now());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter(UPDATED_BY)){
            this.strictUpdateFill(metaObject, UPDATED_BY, String.class, userId());
        }
        if (metaObject.hasGetter(UPDATED_TIME)){
            this.strictUpdateFill(metaObject, UPDATED_TIME, LocalDateTime.class, LocalDateTime.now());
        }
    }

}
